package com.karrim.shared.util;

import com.google.common.hash.Hashing;
import java.io.Serializable;

/**
 *
 * @author andrea.cantafio
 */
public class Message implements Serializable{

    public Message(int code) {
        this.code = code;
        content = "";
    }

    public Message(int code, String content) {
        this.code = code;
        this.content = content == null ? "" : content;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof Message) {
            Message m = (Message) obj;
            return code == m.code && content.equals(m.content);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Hashing.md5().newHasher().putInt(code).putString(content).hashCode();
    }

    @Override
    public String toString() {
        return String.format("%0" + CODE_SIZE + "d", code) + DELIMITER + content;
    }

    public static boolean validate(String message) {
        String[] msg = message.split(String.valueOf(DELIMITER), 2);
        if (msg[0].length() == CODE_SIZE) {
            try {
                Integer.parseInt(msg[0]);
                return true;
            } catch (NumberFormatException nfe) {
                return false;
            }
        }
        return false;
    }
    /**
     * Message codes. Error codes are smaller than 0.
     *
     * [-1;-10] Method not allowed.
     */
    public static final int DELETE_NOT_ALLOWED = -1,
            GET_NOT_ALLOWED = -2,
            POST_NOT_ALLOWED = -3,
            PUT_NOT_ALLOWED = -4;
    public final int code;
    public final String content;
    public static final int CODE_SIZE = 3;
    public static final char DELIMITER = ':';
}
